<template>
  <div
    ref="cardRef"
    class="agent-card"
    @mouseenter="handleMouseEnter"
    @mouseleave="handleMouseLeave"
    @click="handleCardClick"
  >
    <!-- 卡片背景光效 -->
    <div class="card-glow"></div>
    
    <!-- 卡片内容 -->
    <div class="card-content">
      <!-- 卡片头部 -->
      <div class="card-header">
        <div class="agent-avatar">
          <div class="avatar-inner">
            <span class="avatar-text">{{ avatarText }}</span>
          </div>
        </div>
        
        <div class="agent-info">
          <h3 class="agent-name" :title="agent.name">{{ agent.name }}</h3>
          <p class="agent-time">{{ formattedTime }}</p>
        </div>
        
        <!-- 操作按钮组 -->
        <div class="action-buttons">
          <!-- 编辑按钮 -->
          <button
            class="edit-btn"
            @click.stop="handleEdit"
            :title="`编辑 ${agent.name}`"
          >
            <svg class="edit-icon" viewBox="0 0 24 24" fill="none">
              <path
                d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
            </svg>
          </button>
          
          <!-- 删除按钮 -->
          <button
            v-show="false"
            class="delete-btn"
            @click.stop="handleDelete"
            :title="`删除 ${agent.name}`"
          >
            <svg class="delete-icon" viewBox="0 0 24 24" fill="none">
              <path
                d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6h14zM10 11v6M14 11v6"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
            </svg>
          </button>
        </div>
      </div>
      
      <!-- 智能体详细信息 -->
      <div class="agent-details">
        <!-- 作者信息 -->
        <div class="detail-item">
          <span class="detail-label">作者</span>
          <span class="detail-value">{{ agent.author }}</span>
        </div>
        
        <!-- 描述信息 -->
        <div class="detail-item" v-if="agent.description">
          <span class="detail-label">说明</span>
          <span class="detail-value" :title="agent.description">{{ truncatedDescription }}</span>
        </div>
        
        <!-- 分类信息 -->
        <div class="detail-item">
          <span class="detail-label">分类</span>
          <span class="detail-value category-tag">{{ categoryDisplayName }}</span>
        </div>
        
        <!-- 标签信息 -->
        <div class="detail-item" v-if="agent.tags && agent.tags.length > 0">
          <span class="detail-label">标签</span>
          <div class="tags-container">
            <span 
              v-for="tag in displayTags" 
              :key="tag" 
              class="tag-item"
            >
              {{ tag }}
            </span>
            <span v-if="agent.tags.length > 3" class="tag-more">
              +{{ agent.tags.length - 3 }}
            </span>
          </div>
        </div>
      </div>
      
      <!-- 分享链接 -->
      <div class="share-url-container">
        <div class="url-label">分享链接</div>
        <div class="share-url" :title="agent.shareUrl">
          {{ truncatedUrl }}
        </div>
      </div>
      
      <!-- 卡片底部操作区 -->
      <div class="card-actions">
        <button class="action-btn primary" @click.stop="handleVisit">
          <svg class="btn-icon" viewBox="0 0 24 24" fill="none">
            <path
              d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6M15 3h6v6M10 14L21 3"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            />
          </svg>
          访问
        </button>
        
        <button class="action-btn secondary" @click.stop="handleCopyUrl">
          <svg class="btn-icon" viewBox="0 0 24 24" fill="none">
            <path
              d="M16 4h2a2 2 0 012 2v14a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2h2M15 2H9a1 1 0 00-1 1v2a1 1 0 001 1h6a1 1 0 001-1V3a1 1 0 00-1-1z"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            />
          </svg>
          复制
        </button>
      </div>
    </div>
    
    <!-- 边框光效 -->
    <div class="card-border"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import type { Agent } from '../types/agent'
import { getCategoryDisplayName } from '../lib/dict-constant'
import {
  animateCardEnter,
  animateCardHover,
  animateCardHoverOut,
  animateCardClick,
  killAnimations
} from '../services/animationService'

/**
 * 组件属性定义
 */
interface Props {
  /** 智能体数据 */
  agent: Agent
  /** 进入动画延迟 */
  animationDelay?: number
}

/**
 * 组件事件定义
 */
interface Emits {
  /** 编辑事件 */
  edit: [agent: Agent]
  /** 删除事件 */
  delete: [agent: Agent]
  /** 访问事件 */
  visit: [agent: Agent]
  /** 复制链接事件 */
  copy: [agent: Agent]
}

const props = withDefaults(defineProps<Props>(), {
  animationDelay: 0
})

const emit = defineEmits<Emits>()

/** 卡片DOM引用 */
const cardRef = ref<HTMLElement>()

/** 是否悬停状态 */
const isHovered = ref(false)

/**
 * 头像文字计算属性
 * 取智能体名称的首字符
 */
const avatarText = computed(() => {
  return props.agent.name.charAt(0).toUpperCase()
})

/**
 * 格式化时间计算属性
 */
const formattedTime = computed(() => {
  const date = new Date(props.agent.createdAt)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    return '今天'
  } else if (diffDays === 1) {
    return '昨天'
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else {
    return date.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric'
    })
  }
})

/**
 * 截断的URL计算属性
 */
const truncatedUrl = computed(() => {
  const url = props.agent.shareUrl
  if (url.length <= 40) {
    return url
  }
  return url.substring(0, 37) + '...'
})

/**
 * 截断的描述计算属性
 */
const truncatedDescription = computed(() => {
  const description = props.agent.description || ''
  if (description.length <= 50) {
    return description
  }
  return description.substring(0, 47) + '...'
})

/**
 * 分类显示名称计算属性
 */
const categoryDisplayName = computed(() => {
  return getCategoryDisplayName(props.agent.category)
})

/**
 * 显示标签计算属性（最多显示3个）
 */
const displayTags = computed(() => {
  return props.agent.tags?.slice(0, 3) || []
})

/**
 * 处理鼠标进入事件
 */
function handleMouseEnter() {
  isHovered.value = true
}

/**
 * 处理鼠标离开事件
 */
function handleMouseLeave() {
  isHovered.value = false
}

/**
 * 处理卡片点击事件
 */
function handleCardClick() {
  if (!cardRef.value) return
  
  animateCardClick(cardRef.value, {
    onComplete: () => {
      handleVisit()
    }
  })
}

/**
 * 处理编辑按钮点击
 */
function handleEdit() {
  emit('edit', props.agent)
}

/**
 * 处理删除按钮点击
 */
function handleDelete() {
  emit('delete', props.agent)
}

/**
 * 处理访问按钮点击
 */
function handleVisit() {
  emit('visit', props.agent)
  
  // 打开新窗口访问链接
  try {
    window.open(props.agent.shareUrl, '_blank', 'noopener,noreferrer')
  } catch (error) {
    console.error('打开链接失败:', error)
  }
}

/**
 * 处理复制链接按钮点击
 */
async function handleCopyUrl() {
  try {
    await navigator.clipboard.writeText(props.agent.shareUrl)
    emit('copy', props.agent)
  } catch (error) {
    console.error('复制链接失败:', error)
    
    // 降级方案：使用传统方法复制
    const textArea = document.createElement('textarea')
    textArea.value = props.agent.shareUrl
    textArea.style.position = 'fixed'
    textArea.style.opacity = '0'
    document.body.appendChild(textArea)
    textArea.select()
    
    try {
      document.execCommand('copy')
      emit('copy', props.agent)
    } catch (fallbackError) {
      console.error('降级复制方案也失败:', fallbackError)
    } finally {
      document.body.removeChild(textArea)
    }
  }
}

/**
 * 组件挂载时执行进入动画
 */
onMounted(() => {
  if (cardRef.value) {
    animateCardEnter(cardRef.value, {
      delay: props.animationDelay
    })
  }
})

/**
 * 组件卸载时清理动画
 */
onUnmounted(() => {
  if (cardRef.value) {
    killAnimations(cardRef.value)
  }
})
</script>

<style scoped>
.agent-card {
  position: relative;
  background: linear-gradient(135deg, rgba(0, 20, 40, 0.9) 0%, rgba(0, 40, 80, 0.8) 100%);
  border: 1px solid rgba(50, 236, 138, 0.3);
  border-radius: 5px;
  padding: 20px;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 25px rgba(50, 236, 138, 0.15);
}

.card-glow {
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(50, 236, 138, 0.1) 0%, transparent 70%);
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;
}



.card-content {
  position: relative;
  z-index: 2;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.agent-avatar {
  flex-shrink: 0;
}

.avatar-inner {
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #32ec8a 0%, #28c470 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(50, 236, 138, 0.3);
}

.avatar-text {
  color: #000;
  font-weight: bold;
  font-size: 18px;
}

.agent-info {
  flex: 1;
  min-width: 0;
}

.agent-name {
  color: #32ec8a;
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 4px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-shadow: 0 0 10px rgba(50, 236, 138, 0.5);
}

.agent-time {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
  margin: 0;
}

.action-buttons {
  position: absolute;
  top: 8px;
  right: 8px;
  display: flex;
  gap: 6px;
}

.edit-btn,
.delete-btn {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  border: 1px solid;
}

.edit-btn {
  background: rgba(50, 236, 138, 0.1);
  border-color: rgba(50, 236, 138, 0.3);
  color: rgba(50, 236, 138, 0.8);
}

.edit-btn:hover {
  background: rgba(50, 236, 138, 0.2);
  border-color: rgba(50, 236, 138, 0.5);
  color: #32ec8a;
  transform: scale(1.1);
  box-shadow: 0 0 12px rgba(50, 236, 138, 0.4);
}

.delete-btn {
  background: rgba(40, 196, 112, 0.1);
  border-color: rgba(40, 196, 112, 0.3);
  color: rgba(40, 196, 112, 0.8);
}

.delete-btn:hover {
  background: rgba(40, 196, 112, 0.2);
  border-color: rgba(40, 196, 112, 0.5);
  color: #28c470;
  transform: scale(1.1);
  box-shadow: 0 0 12px rgba(40, 196, 112, 0.4);
}

.edit-icon,
.delete-icon {
  width: 16px;
  height: 16px;
}

.share-url-container {
  margin-bottom: 20px;
}

.url-label {
  color: rgba(255, 255, 255, 0.7);
  font-size: 12px;
  margin-bottom: 6px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.share-url {
  color: rgba(50, 236, 138, 0.8);
  font-size: 14px;
  font-family: 'Courier New', monospace;
  background: rgba(50, 236, 138, 0.1);
  padding: 8px 12px;
  border-radius: 4px;
  border: 1px solid rgba(50, 236, 138, 0.2);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 智能体详细信息样式 */
.agent-details {
  margin: 16px 0;
  padding: 12px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 4px;
  border: 1px solid rgba(50, 236, 138, 0.1);
}

.detail-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 8px;
  min-width: 0;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-label {
  flex-shrink: 0;
  font-size: 12px;
  color: rgba(50, 236, 138, 0.8);
  font-weight: 500;
  min-width: 32px;
}

.detail-value {
  flex: 0 1 auto;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
  line-height: 1.4;
  word-break: break-word;
  min-width: 0;
}

.category-tag {
  display: inline-block;
  background: linear-gradient(135deg, rgba(50, 236, 138, 0.2) 0%, rgba(40, 196, 112, 0.2) 100%);
  color: #32ec8a;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
  border: 1px solid rgba(50, 236, 138, 0.3);
  width: auto;
  min-width: fit-content;
  max-width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex-shrink: 0;
  box-sizing: border-box;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
}

.tag-item {
  display: inline-block;
  background: rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.8);
  padding: 2px 6px;
  border-radius: 8px;
  font-size: 10px;
  font-weight: 400;
  border: 1px solid rgba(255, 255, 255, 0.2);
  white-space: nowrap;
}

.tag-more {
  font-size: 10px;
  color: rgba(255, 255, 255, 0.6);
  font-style: italic;
}

.card-actions {
  display: flex;
  gap: 12px;
}

.action-btn {
  flex: 1;
  height: 36px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  transition: all 0.3s ease;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.action-btn.primary {
  background: linear-gradient(135deg, #32ec8a 0%, #28c470 100%);
  color: #000;
  box-shadow: 0 4px 12px rgba(50, 236, 138, 0.3);
}

.action-btn.primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(50, 236, 138, 0.4);
}

.action-btn.secondary {
  background: rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.action-btn.secondary:hover {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
  border-color: rgba(255, 255, 255, 0.4);
  transform: translateY(-2px);
}

.btn-icon {
  width: 16px;
  height: 16px;
}

.card-border {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-radius: 5px;
  padding: 1px;
  background: linear-gradient(135deg, transparent 0%, rgba(50, 236, 138, 0.5) 50%, transparent 100%);
  mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
  mask-composite: exclude;
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;
}



/* 响应式设计 */
@media (max-width: 768px) {
  .agent-card {
    padding: 16px;
  }
  
  .card-header {
    gap: 10px;
  }
  
  .avatar-inner {
    width: 40px;
    height: 40px;
  }
  
  .avatar-text {
    font-size: 16px;
  }
  
  .agent-name {
    font-size: 16px;
  }
  
  .action-btn {
    height: 32px;
    font-size: 12px;
  }
  
  .agent-details {
    margin: 12px 0;
    padding: 10px;
  }
  
  .detail-label {
    min-width: 28px;
    font-size: 11px;
  }
  
  .detail-value {
    font-size: 11px;
  }
  
  .category-tag {
    font-size: 10px;
    padding: 1px 6px;
  }
  
  .tag-item {
    font-size: 9px;
    padding: 1px 4px;
  }
  
  .tag-more {
    font-size: 9px;
  }
  
  .action-buttons {
    top: 6px;
    right: 6px;
    gap: 4px;
  }
  
  .edit-btn,
  .delete-btn {
    width: 28px;
    height: 28px;
  }
  
  .edit-icon,
  .delete-icon {
    width: 14px;
    height: 14px;
  }
}
</style>